from __future__ import annotations

import enum
from sqlalchemy import func
from .. import db


class ArticleVisibility(str, enum.Enum):
	public = "public"
	private = "private"


class Article(db.Model):
	__tablename__ = "articles"

	id = db.Column(db.Integer, primary_key=True)
	title = db.Column(db.String(200), nullable=False)
	content = db.Column(db.Text, nullable=False)
	visibility = db.Column(db.Enum(ArticleVisibility), default=ArticleVisibility.public, nullable=False)
	author_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False, index=True)
	created_at = db.Column(db.DateTime, nullable=False, server_default=func.now())
	updated_at = db.Column(db.DateTime, nullable=False, server_default=func.now(), onupdate=func.now())

	author = db.relationship("User", backref=db.backref("articles", lazy=True))

	def to_dict(self) -> dict:
		return {
			"id": self.id,
			"title": self.title,
			"content": self.content,
			"visibility": self.visibility.value if self.visibility else None,
			"author_id": self.author_id,
			"created_at": self.created_at.isoformat() if self.created_at else None,
			"updated_at": self.updated_at.isoformat() if self.updated_at else None,
		}


